package org.devf.fork.imsimulator.help;

import cn.hutool.core.lang.TypeReference;
import cn.hutool.json.JSONUtil;
import org.devf.fork.imsimulator.http.pojo.ApiResult;

import java.util.function.Consumer;
import java.util.function.Supplier;

/**
 * ApiResultHelp related
 *
 * @author wanghuafu
 * @since 0.1 2023/9/12
 */
public class ApiResultHelp {

    public static ApiResultHelp util = new ApiResultHelp();

    public <T> T unwrapIfSuccess(Supplier<ApiResult<T>> supplier){
        ApiResult<T> apiResult = supplier.get();
        if (apiResult.getCode() == 0){
            return apiResult.getData();
        }else{
            return null;
        }
    }

    public <T> T unwrapIfSuccess2(Supplier<String> supplier){
        ApiResult<T> apiResult = JSONUtil.toBean(supplier.get(), new TypeReference<>() {
        },false);
        if (apiResult.getCode() == 0){
            return apiResult.getData();
        }else{
            return null;
        }
    }

    public void unwrapIfSuccessElse(Object contents, Consumer<Object> suc , Consumer<Object> fail) {
        ApiResult<?> baseResults = JSONUtil.toBean(contents.toString(), ApiResult.class);
        if (baseResults.getCode() == 0) {
            suc.accept(baseResults.getData());
        } else {
            fail.accept(baseResults.getMsg());
        }
    }
}
